package org.xwebwork.lucene;

import java.io.File;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class TxtFileIndexer {

    public static void main(String[] args) {
        try {
            File indexDir = new File("/home/playboy/work/lucene/luceneIndex");
            Directory directory = FSDirectory.open(indexDir);
            
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43);
            IndexWriterConfig config =  new IndexWriterConfig(Version.LUCENE_43, analyzer);
            
            IndexWriter indexwriter = new IndexWriter(directory, config);

            Document doc = new Document();
            doc.add(new Field("fieldname", "This is the text to be indexed.", TextField.TYPE_STORED));
            indexwriter.addDocument(doc);
            indexwriter.close();

            // Now search the index:
            DirectoryReader ireader = DirectoryReader.open(directory);
            IndexSearcher isearcher = new IndexSearcher(ireader);
            // Parse a simple query that searches for "text":
            QueryParser parser = new QueryParser(Version.LUCENE_43, "fieldname", analyzer);
            Query query = parser.parse("text");
            ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
            // Iterate through the results:
            for (int i = 0; i < hits.length; i++) {
                Document hitDoc = isearcher.doc(hits[i].doc);
            }
            ireader.close();
            directory.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
